package com.yrline.pay.services;

import java.math.BigDecimal;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.yrline.pay.proxy.request.AssureProjectRequest;
import com.yrline.pay.proxy.request.ProjectRegRequest;
import com.yrline.pay.services.vo.ProjectVo;
import com.yrline.pay.services.vo.UserVo;

@Service
public class ProjectServices {

	@Autowired
	private StringRedisTemplate redisCached;

	@Autowired
	private UserServices userServices;

	private static String project_key = "PROJECT_INFO";

	public void save(ProjectRegRequest p) {

		ProjectVo pv = new ProjectVo();
		BeanUtils.copyProperties(p, pv);
		pv.setAvaAmount(p.getProjectAmt());
		redisCached.opsForHash().put(project_key, pv.getProjectNo(), pv);

	}

	public List<ProjectVo> selectAll() {
		return (List<ProjectVo>) (List) redisCached.opsForHash().values(
				project_key);
	}

	public ProjectVo getProject(String projectNo) {
		return (ProjectVo) redisCached.opsForHash().get(project_key, projectNo);
	}

	public void inverst(String projectNo, BigDecimal amount) {
		ProjectVo p = getProject(projectNo);
		BigDecimal avaAmount = p.getAvaAmount() == null ? BigDecimal.ZERO : p
				.getAvaAmount();
		BigDecimal loanAmount = p.getLoanAmount() == null ? BigDecimal.ZERO : p
				.getLoanAmount();
		BigDecimal _a = avaAmount.subtract(amount);
		BigDecimal _l = loanAmount.add(amount);
		p.setAvaAmount(_a);
		p.setLoanAmount(_l);
		redisCached.opsForHash().put(project_key, p.getProjectNo(), p);

	}

	public void subLoanAmount(String projectNo, BigDecimal amount) {
		ProjectVo p = getProject(projectNo);
		BigDecimal _l = p.getLoanAmount().subtract(amount);
		p.setLoanAmount(_l);
		redisCached.opsForHash().put(project_key, p.getProjectNo(), p);
	}

	public void assureProject(AssureProjectRequest req) {
		UserVo _uv = userServices.selectUserOne(req.getAssureIpsAcctNo(),
				req.getAssureType());
		ProjectVo _pv = this.getProject(req.getProjectNo());
		_pv.setAssureIpsAcctNo(req.getAssureIpsAcctNo());
		_pv.setAssureMobile(_uv.getMobileNo());
		_pv.setAssureName(_uv.getRealName());
		_pv.setAssureType(req.getAssureType());
		_pv.setAssureAmount(req.getAssureAmt());
		_pv.setAssureIncome(req.getAssureIncome());
		redisCached.opsForHash().put(project_key, _pv.getProjectNo(), _pv);
	}

}
